package com.itboye.ihomebank.util;

import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.google.gson.Gson;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.AvatarBeans;
import com.itboye.ihomebank.bean.AvatarDataBeans;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

/**
 * 上传图片
 * 
 */
public class UploadImage {
	private static final MediaType MEDIA_TYPE_PNG = MediaType
			.parse("image/png");
	private ExecutorService executorService;
	private static UploadImage upload;

	private UploadImage() {
		executorService = Executors.newFixedThreadPool(4);
	}

	/**
	 * 单例
	 * 
	 * @return
	 */
	public static synchronized UploadImage getInstance() {
		if (upload == null) {
			upload = new UploadImage();
		}

		return upload;
	}

	public void execute(final String[] url, final String type,
			final OnUploadlistener uploadListener, final Object otherData) {
		executorService.execute(new Runnable() {

			@Override
			public void run() {

				Handler handler = new Handler(Looper.getMainLooper()) {
					@Override
					public void handleMessage(android.os.Message msg) {
						switch (msg.what) {
						case 0:
							ArrayList<AvatarDataBeans> resultData = (ArrayList<AvatarDataBeans>) msg.obj;
							uploadListener.OnSuccess(resultData);
							break;
						case 1:
							String errorInfo = "上传失败";
							uploadListener.OnError(errorInfo);
							break;
						default:
							break;
						}
					}
				};

				try {
					OkHttpClient client = new OkHttpClient();
					client.setConnectTimeout(10, TimeUnit.SECONDS);
					client.setReadTimeout(10, TimeUnit.SECONDS);
					client.setWriteTimeout(10, TimeUnit.SECONDS);

					for (int i = 0; i < url.length; i++) {
						File file = new File(url[i]);

						System.out.println("uid"
								+ (String) SPUtils.get(MyApplcation.ctx, null,
										SPContants.USER_ID, "") + "?>"
								+ file.getName());
						// 创建请求BODY
						MultipartBuilder requestBody = new MultipartBuilder()
								.type(MultipartBuilder.FORM)
								.addFormDataPart(
										"uid",
										(String) SPUtils.get(MyApplcation.ctx,
												null, SPContants.USER_ID, ""))
								.addFormDataPart("type", type)
								.addFormDataPart(
										"image",
										file.getName(),
										RequestBody
												.create(MEDIA_TYPE_PNG, file));
						if (otherData != null) {
							requestBody.addFormDataPart("house_no",
									otherData.toString());
						}

						Request request = new Request.Builder()
								.url(NetPublicConstant.URL
										+ "/file/upload?client_id=by565fa4facdb191")
								.post(requestBody.build()).build();

						Response response = client.newCall(request).execute();

						if (!response.isSuccessful()) {
							handler.sendEmptyMessage(1);
						} else {
							String result = response.body().string();
							System.out.println("图片上传的结果" + "" + result);

							Gson gson = new Gson();
							AvatarBeans avatarBeans = null;
							try {
								avatarBeans = gson.fromJson(result,
										AvatarBeans.class);// 获取到网络端数据,多个参数
								Message msg = new Message();
								if (avatarBeans.getCode() == 0) {
									msg.what = 0;
									msg.obj = avatarBeans.getData();
									handler.sendMessage(msg);
								} else {
									msg.what = 1;
									msg.obj = avatarBeans.getData();
									handler.sendMessage(msg);
								}
							} catch (Exception e) {
								// TODO: handle exception
								Message msg = new Message();
								JSONObject jsonObject = new JSONObject(result);
								String data = jsonObject.getString("data");
								msg.what = 1;
								msg.obj = data;
								handler.sendMessage(msg);
							}

						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 
	 * @author winter 要实现的接口
	 */
	public interface OnUploadlistener {

		public void OnSuccess(ArrayList<AvatarDataBeans> resultData);

		public void OnError(String resultData);

	}

}
